//
//  AppNetworkingManager.m
//  OA
//
//  Created by Guo Rui on 2017/9/26.
//Copyright © 2017年 GR Harry. All rights reserved.
//

#import "AppNetworkingManager.h"
#import <YYModel/YYModel.h>
#import "TFPopoverManager.h"
#import <SDWebImage/NSData+ImageContentType.h>
#import <MobileCoreServices/UTType.h>

@implementation AppNetworkingManager

#pragma mark - 具体各个模块的请求方法
//示例方法
//+ (void)registerWithParams:(NSDictionary *)params responseBlock:(void (^)(XXXUserModel *, NSError *))responseBlock {
//    [self startRequestWithParams:params path:@"register interface path" responseMapClassName:@"AppBaseModel" responseObjectPath:kAppBaseModelResponseObjectPath popoverProgressString:@"注册中..." handleErrorAutomatically:YES responseBlock:responseBlock];
//}

#pragma mark - 公共请求方法

+ (AppBaseRequest *)startRequestWithParams:(id)params
                                      path:(NSString *)url
                        responseObjectPath:(NSString *)responseObjectPath
                     popoverProgressString:(NSString *)popoverProgressString
                  handleErrorAutomatically:(BOOL)handleErrorAutomatically
                             responseBlock:(void (^)(id, NSError *))responseBlock{
    return [self startRequestWithParams:params
                                   path:url
                       constructingBody:nil
                     responseObjectPath:responseObjectPath
                  popoverProgressString:popoverProgressString
               handleErrorAutomatically:handleErrorAutomatically
                          responseBlock:responseBlock];
}

+ (AppBaseRequest *)startRequestWithParams:(id)params
                                      path:(NSString *)url
                          constructingBody:(TFConstructingBodyBlock)constructingBody
                        responseObjectPath:(NSString *)responseObjectPath
                     popoverProgressString:(NSString *)popoverProgressString
                  handleErrorAutomatically:(BOOL)handleErrorAutomatically
                             responseBlock:(void (^)(id, NSError *))responseBlock {
    
    AppBaseRequest *request = [[AppBaseRequest alloc] init];
    request.path = url;
    request.params = params;
    if (constructingBody) {
        request.timeoutInterval = 200.0;
        request.construtingBodyBlock = constructingBody;
    }
    else {
        request.timeoutInterval = 10;
    }
    if (popoverProgressString) {
        [TFPopoverManager showPopoverViewWithViewType:TFPopoverTypeStatus text:popoverProgressString];
    }
    
    [request startRequestWithResponseBlock:^(__kindof TFRequest * _Nonnull request, __kindof id _Nullable response, NSError * _Nullable error) {
        if (popoverProgressString) {
            [TFPopoverManager dismissPopoverView];
        }
        
        NSError *responseError = error;
        if (responseError == nil) {
            responseError = request.error;
        }
        
        //判断是否有错误
        if (responseError) {
            //判断是否自动处理错误
            if (handleErrorAutomatically) {
                //自动处理则弹出提示层
                [TFPopoverManager showPopoverViewWithViewType:TFPopoverTypeFail text:responseError.localizedDescription];
                  responseBlock(nil,responseError);
            }
            else {
                //自己处理，则返回结果
                if (responseBlock) {
                    responseBlock(nil,responseError);
                }
            }
        }
        else {
            //根据path做模型转换
            id responseObject = response;
            if (responseObjectPath.length) {
                responseObject = [response valueForKeyPath:responseObjectPath];
            }
            if (responseBlock) {
                responseBlock(responseObject,responseError);

            }
        }
        
    }];
    return request;
}

+ (void)appendImageDataWithImages:(NSArray *)images formData:(id<AFMultipartFormData>)formData
{
    for (int i = 0; i < images.count; i ++) {
        
        UIImage *image = images[i];
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
        
        NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
        formatter.dateFormat=@"yyyyMMddHHmmss";
        NSString *str=[formatter stringFromDate:[NSDate date]];
        NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:[self mineTypeWithImageData:imageData]];
    }
}

+ (NSString *)mineTypeWithImageData:(NSData *)imageData
{
    CFStringRef stringRef = [NSData sd_UTTypeFromSDImageFormat:[NSData sd_imageFormatForImageData:imageData]];
    NSString *MIMEType = (__bridge NSString *)UTTypeCopyPreferredTagWithClass (stringRef, kUTTagClassMIMEType);
    if (!MIMEType) {
        MIMEType = @"application/octet-stream";
    }
    
    CFRelease(stringRef);
    return MIMEType;
}

@end
